<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="https://www.thymeleaf.org"
    xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/public.css" media="all">
    <link rel="stylesheet" href="/static/admin/permission/css/loading.css">
    <style>
        .ui-input-class{
            width: 60%;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
            </div>
        </script>

        <table class="layui-hide" id="menuTableId" lay-filter="employeeTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-warm layui-btn-xs data-count-edit" lay-event="edit">赋予角色</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除菜单</a>
        </script>

    </div>

    <!-- 给菜单添加角色 -->
    <div id="addRoleByMenu" style="display: none;">

        <form class="layui-form" action="">
            <div class="layui-form-item">
                <label class="layui-form-label">赋予角色</label>

                <div class="layui-input-block" id="roleCheckBoxDiv">

                </div>
            </div>
        </form>

    </div>

</div>
<!-- 菜单头工具 -->
<div id="menuToolBar" style="display: none">

    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="addMenu" shiro:hasPermission="role:add"> 添加 </button>
    </div>

</div>

<!-- 菜单弹出 添加菜单界面 -->
<div id="menuAddOpen" style="display: none;">

    <div class="layui-form layuimini-form">
        <div class="layui-form-item" style="margin-top: 20px;">
            <label class="layui-form-label required">菜单名称</label>
            <div class="layui-input-inline">
                <input type="text" name="menuName" lay-verify="required" lay-reqtext="菜单名称不能为空" placeholder="请输入菜单名称"  value="" class="layui-input ui-input-class">
            </div>

            <label class="layui-form-label required">菜单描述</label>
            <div class="layui-input-inline">
                <input type="text" name="menuDetails" lay-verify="required" lay-reqtext="菜单描述不能为空" placeholder="请输入菜单描述"  value="" class="layui-input ui-input-class">
            </div>
        </div>

        <div class="layui-form-item">
            <label class="layui-form-label required">菜单图标</label>
            <div class="layui-input-inline">
                <input type="text" name="menuIcon" lay-verify="required" lay-reqtext="菜单图标不能为空" placeholder="请输入菜单图标"  value="" class="layui-input ui-input-class">
            </div>

            <label class="layui-form-label required">菜单链接</label>
            <div class="layui-input-inline">
                <input type="text" name="menuUrl" lay-verify="required" lay-reqtext="菜单链接不能为空" placeholder="请输入菜单链接"  value="" class="layui-input ui-input-class">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">选择上级菜单</label>
            <div class="layui-input-inline">
                <!-- 加载 -->
                <div class="windows8" id="loading">
                    <div class="wBall" id="wBall_1">
                        <div class="wInnerBall"></div>
                    </div>
                    <div class="wBall" id="wBall_2">
                        <div class="wInnerBall"></div>
                    </div>
                    <div class="wBall" id="wBall_3">
                        <div class="wInnerBall"></div>
                    </div>
                    <div class="wBall" id="wBall_4">
                        <div class="wInnerBall"></div>
                    </div>
                    <div class="wBall" id="wBall_5">
                        <div class="wInnerBall"></div>
                    </div>
                </div>
                <div id="menuTreeDiv"></div>
            </div>

            <label class="layui-form-label required">可访问角色</label>
            <div class="layui-input-inline" id="roleCheckBox">

            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
            </div>
        </div>
    </div>

</div>


<script src="/static/admin/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    layui.config({
        base: '/static/admin/js//lay-module/treetable-lay/'

    }).use(['form', 'table','treeTable','tree'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var treeTable = layui.treeTable;
        var tree = layui.tree;

        treeTable.render({
            elem: '#menuTableId',
            url: '/admin/queryMenuRoleMap',
            toolbar: '#menuToolBar',
            tree: {
                iconIndex: 2,           // 折叠图标显示在第几列
                isPidData: true,        // 是否是id、pid形式数据
                idName: 'menuId',  // id字段名称
                pidName: 'menuManager'     // pid字段名称
            },
            defaultToolbar: [],
            cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'menuId', title: '菜单id'},
                    {field: 'menuName', title: '菜单名字名字'},
                    {field: 'menuUrl', title: '菜单跳转地址'},
                    {field: 'menuDetails', title: '菜单描述'},
                    {
                        title: '可访问角色', templet: function (res) {
                            var html = '';

                            $.each(res.roleList, function (index, item) {
                                html += '<span class="layui-badge layui-bg-blue">' + item.roleName + '</span> | ';

                            })

                            return html;
                        }
                    },
                    {fixed: 'right', title: '操作', align: 'center', toolbar: '#currentTableBar'}
                ]
            ]
        });

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            //获取树形菜单选中的节点
            var checkData = tree.getChecked('menuTreeId');
            var menuManagerId = 0;
            console.log(checkData.length);
            if (checkData.length > 1){
                layer.msg("只可选择一个一级菜单")
                return false;
            }

            if (checkData.length > 0){
                //上级菜单id
                menuManagerId = checkData[0].id;
            }
            //获取角色复选框
            var roleId = [];
            $("input[name='roleId']:checked").each(function () {

                roleId.push($(this).val());

            })
            if (roleId.length == 0){
                layer.msg("最少选择一个角色");
                return false;
            }
            data.field.roleIdList = roleId.join("-");
            data.field.menuManager = menuManagerId;

            $.ajax({
                url:'/admin/addMenu',
                type:'post',
                data:data.field,
                dataType:'json',
                success:function (res) {

                    layer.msg(res.message,function () {
                        //刷新表格
                        treeTable.reload('menuTableId', {
                            url: '/admin/queryMenuRoleMap'

                        });
                    });

                }
            })

            return false;
        })

        //监听表格头部事件
        treeTable.on('toolbar(menuTableId)', function(obj){

            switch(obj.event){
                case 'addMenu':

                    layer.open({
                        type: 1,
                        area:['700px','700px'],
                        content: $('#menuAddOpen'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        success:function (layero, index) {
                            $('#loading').show()
                            $('#menuTreeDiv').html("");
                            //刷新出复选框
                            $.ajax({
                                url:'/admin/queryAllRole',
                                type:'post',
                                dataType:'json',
                                success:function (res) {
                                    var html = '';
                                    $.each(res.data,function (index,item) {
                                        html += '<input type="checkbox" name="roleId" title="'+item.roleName+'" value="'+item.roleId+'">';
                                    })

                                    $('#roleCheckBox').html(html);

                                    form.render(); //更新全部
                                }
                            })

                            //渲染菜单
                            $.ajax({
                                url:'/admin/queryMenuTree/0',
                                type:'post',
                                dataType:'json',
                                async: true,
                                success:function (res) {

                                    if (res.code == 200){
                                        $('#loading').hide()
                                        //渲染树形
                                        var inst1 = tree.render({
                                            elem: '#menuTreeDiv'  //绑定元素
                                            ,id:'menuTreeId'
                                            , showCheckbox: true
                                            , showLine:true
                                            ,data: res.data


                                        });

                                    } else {

                                        layer.msg(res.message)

                                    }



                                }
                            })



                        }
                    });


                    break;
            };
        });

        //监听工具行
        treeTable.on('tool(menuTableId)', function (obj) {
            var data = obj.data;

            if (obj.event === 'edit') {

                var index = layer.open({
                    title: '赋予角色',
                    type: 1,
                    area: ['500px', '300px'],
                    content: $('#addRoleByMenu'),
                    success:function (layer,index) {

                        //获取全部角色
                        $.ajax({
                            url:'/admin/queryAllRo/'+data.menuId,
                            type:'post',
                            dataType:'',
                            success:function (res) {

                                if (res.code == 200){

                                    var html = '';
                                    //所有角色信息
                                    var allRole = res.data.allRole;
                                    var roleByMenuId = res.data.roleByMenuId;

                                    $.each(allRole,function (index,it) {
                                        var count =0;

                                        $.each(roleByMenuId,function (index,item) {

                                            if (item.roleId == it.roleId){
                                                count++;


                                                return false;
                                            }

                                        })
                                        if (count >0){
                                            html += '<input type="checkbox" lay-filter="checkboxFilter" name="roleId" title="'+it.roleName+'" value="'+it.roleId+'" checked data-id="'+data.menuId+'">';
                                        }else{
                                            html += '<input type="checkbox" lay-filter="checkboxFilter" name="roleId" title="'+it.roleName+'" value="'+it.roleId+'" data-id="'+data.menuId+'">';
                                        }

                                    })

                                    $('#roleCheckBoxDiv').html(html);

                                    form.render();
                                } else{

                                    layer.msg(res.message)

                                }

                            }
                        })

                        /*$.ajax({
                            url:'/admin/queryRoleByMenuId/'+data.menuId,
                            type:'post',
                            dataType:'json',
                            success:function (res) {

                                if (res.code == 200){


                                } else{

                                    layer.msg(res.message)

                                }

                            }
                        })*/

                    },
                    cancel: function(index, layero){

                        layer.confirm('确定要关闭吗?', {icon: 3, title:'提示'}, function(inde){

                            layer.close(inde);
                            layer.close(index);

                        });

                        return false;
                    }
                });

            }else if(obj.event === 'del'){
                console.log(data)
                layer.confirm('确认要删除吗？', {
                    btn : [ '确定', '取消' ]//按钮
                }, function(index) {

                    //判断菜单有木有下级
                    if (data.children.length >0){
                        layer.msg("一级菜单下有二级菜单不可直接删除")
                    }else{

                        $.ajax({
                            url:'/admin/deleteMenuByMenuId/'+data.menuId,
                            type:'post',
                            dataType:'json',
                            success:function (res) {

                                if (res.code == 200){
                                    layer.msg(res.message,function () {
                                        //刷新表格
                                        treeTable.reload('menuTableId', {
                                            url: '/admin/queryMenuRoleMap'

                                        });
                                    })
                                }

                                layer.msg(res.message)


                            }
                        })

                    }


                    layer.close(index);

                });

            }
        });

        //复选框监听
        form.on('checkbox(checkboxFilter)', function(data){

            //获取菜单id
            var elem = data.elem;

            console.log(elem.getAttribute("data-id"))

            var check = data.elem.checked;
            //赋予角色
            if (check){
                addMenuRole("/admin/addMenuRole/"+elem.getAttribute("data-id")+"/"+data.value);

            }else{//删除角色
                addMenuRole("/admin/deleteMenuRole/"+elem.getAttribute("data-id")+"/"+data.value);
            }


        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            layer.alert(result, {
                title: '最终的搜索信息'
            });

            //执行搜索重载
            table.reload('menuTableId', {
                page: {
                    curr: 1
                }
                , where: {
                    searchParams: result
                }
            }, 'data');

            return false;
        });


        //监听表格复选框选择
        treeTable.on('checkbox(employeeTableFilter)', function (obj) {
            console.log(obj)
        });

        //添加角色菜单表
        function addMenuRole(url) {

            $.ajax({
                url: url,
                type:'post',
                dataType:'',
                success:function (res) {

                    //刷新表格
                    treeTable.reload('menuTableId', {
                        url: '/admin/queryMenuRoleMap'

                    });

                    layer.msg(res.message);

                }
            })

        }

    });
</script>

</body>
</html>
